/* Copyright (c) 2013 fab-o-lab

 Permission is hereby granted, free of charge, to any person
 obtaining a copy of this software and associated documentation
 files (the "Software"), to deal in the Software without
 restriction, including without limitation the rights to use,
 copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the
 Software is furnished to do so, subject to the following
 conditions:

 The above copyright notice and this permission notice shall be
 included in all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
*/

package com.fabolab.android.app.jetset;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;

import com.fabolab.Utils;
import com.fabolab.jetset.core.Server;
import com.fabolab.jetset.core.servlet.Servlet;

import android.annotation.TargetApi;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Environment;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.widget.Toast;

@TargetApi(8)
public class ServerService extends Service {
	private static final String TAG = "ServerService";
	public static final String PREFS_NAME = "JetSetPrefs";
	private com.fabolab.jetset.core.config.model.Context context = new com.fabolab.jetset.core.config.model.Context();
	ServerThread serverThread = null;;
	WakeLock wakeLock = null;
	private int port;
	private static String[] assetArray = {"core/css/bootstrap-responsive.css","core/css/bootstrap-responsive.min.css",
		"core/css/bootstrap.css","core/css/bootstrap.min.css",
		"core/img/glyphicons-halflings-white.png","core/img/glyphicons-halflings.png",
		"core/js/bootstrap.js","core/js/bootstrap.min.js",
		"core/js/jquery-1.9.1.js","core/js/jquery-1.9.1.min.js","core/js/jquery-migrate-1.1.1.js",
		"admin/admin.html","admin/main.html"
		};

	@Override
	public IBinder onBind(Intent intent) {
		Log.d(TAG, "onBind");
		return null;
	}

	@Override
	public void onCreate() {
		Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
		// Restore preferences
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		this.port = settings.getInt("port", 9090);

		boolean mExternalStorageAvailable = false;
		boolean mExternalStorageWriteable = false;
		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state)) {
			// We can read and write the media
			mExternalStorageAvailable = mExternalStorageWriteable = true;
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			// We can only read the media
			mExternalStorageAvailable = true;
			mExternalStorageWriteable = false;
		} else {
			// Something else is wrong. It may be one of many other states, but
			// all we need
			// to know is we can neither read nor write
			mExternalStorageAvailable = mExternalStorageWriteable = false;
		}
		Log.d(TAG, "1mExternalStorageAvailable=" + mExternalStorageAvailable);
		Log.d(TAG, "mExternalStorageWriteable=" + mExternalStorageWriteable);
		if (mExternalStorageAvailable) {
			Log.d(TAG, "external path: [" + getExternalFilesDir(TAG).getPath() + "]");
			context.setDocumentPath(getExternalFilesDir(null).getPath());
			context.setPublishPath(getExternalFilesDir(null).getPath());
			context.setTemplate(getExternalFilesDir(null).getPath());
			//TODO: for wiki servlet
			context.setPublishTemplate("");
			context.setPort(settings.getInt("port", 9090));
		}
		(new File(getExternalFilesDir(null).getPath() +  File.separator + "core/css")).mkdirs();
		(new File(getExternalFilesDir(null).getPath() +  File.separator + "core/img")).mkdirs();
		(new File(getExternalFilesDir(null).getPath() +  File.separator + "core/js")).mkdirs();
		(new File(getExternalFilesDir(null).getPath() +  File.separator + "admin")).mkdirs();
		(new File(getExternalFilesDir(null).getPath() +  File.separator + "vakantiebungalow/css")).mkdirs();
		(new File(getExternalFilesDir(null).getPath() +  File.separator + "vakantiebungalow/gallery/thumbs")).mkdirs();
		(new File(getExternalFilesDir(null).getPath() +  File.separator + "vakantiebungalow/images")).mkdirs();
		
		for(int t =0; t < assetArray.length; t++){

			try {
				InputStream is = getAssets().open(assetArray[t]);
				FileWriter fw = new FileWriter(new File(getExternalFilesDir(null).getPath() +  File.separator + assetArray[t])); 
				Utils.copyStream(is, fw);
				is.close();
				fw.close();
				Log.d(TAG, "copy asset ["+ assetArray[t] + "] : success");
			} catch (IOException e) {
				Log.d(TAG, "open asset ["+ assetArray[t] + "] : failed : " + e.getMessage());
			}
		}
		Log.d(TAG, "onCreate");

	}

	@Override
	public void onDestroy() {
		wakeLock.release();
		serverThread.getServe().setRunning(false);
		Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
		Log.d(TAG, "onDestroy");

	}

	@Override
	public void onStart(Intent intent, int startid) {
		PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "JetSet");
		wakeLock.acquire();

		if (serverThread == null) {
			serverThread = new ServerThread(String.valueOf(this.port), context,this);
		}
		serverThread.start();
		Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
		Log.d(TAG, "onStart");

	}

	class ServerThread extends Thread {
		private Server serve;

		private com.fabolab.jetset.core.config.model.Context context;
		
		private Service service;

		public ServerThread(String str, com.fabolab.jetset.core.config.model.Context context,Service service) {
			super(str);
			this.context = context;
			this.service = service;
		}

		public void run() {

			int port = 9090;
			String throttles = null;
			// Create the server.
			serve = new Server(port, context, service);

			// And add the standard Servlets.
			if (throttles == null){
				serve.addDefaultServlets();
				serve.addWebAppServlets();
			} else
				try {
					serve.addDefaultServlets(true, throttles);
					serve.addWebAppServlets();
				} catch (IOException e) {
					Log.d(TAG, "Problem reading throttles file: " + e);
				}
			Log.d(TAG, "Server instance created");
			serve.serve();
		}

		public com.fabolab.jetset.core.config.model.Context getContext() {
			return context;
		}

		public void setContext(com.fabolab.jetset.core.config.model.Context context) {
			this.context = context;
		}

		public Server getServe() {
			return serve;
		}

		public void setServe(Server serve) {
			this.serve = serve;
		}
	}

}
